package cn.amoqi.springboot.redis.subscriptions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;

@Configuration
public class MessageConfiguration {

    private RedisConnectionFactory redisConnectionFactory;
    private MessageSubscriber messageSubscriber;

    @Autowired
    public void setRedisConnectionFactory(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    @Autowired
    public void setMessageSubscriber(MessageSubscriber messageSubscriber) {
        this.messageSubscriber = messageSubscriber;
    }

    @Bean
    public RedisMessageListenerContainer redisContainer() {
        RedisMessageListenerContainer container
            = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(messageSubscriber, topic());
        return container;
    }

    private Topic topic() {
        return new ChannelTopic("topic");
    }

}